<?php

namespace App\Admin\Controllers\Admin;

use Encore\Admin\Widgets\Form;
use Illuminate\Http\Request;
use App\Models\Setting as SettingModel;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Redis;

class FlowChannelCheck extends Form
{
    /**
     * The form title.
     *
     * @var string
     */
    public $title = '检测设置';

    /**
     * Handle the form request.
     *
     * @param Request $request
     *
     * @return \Illuminate\Http\RedirectResponse
     */
    public function handle(Request $request)
    {

        $check_switch = $request->check_switch == 'on' ? 1 : 0;
        SettingModel::query()->updateOrCreate(['key' => 'check_switch'], ['value' => json_encode($check_switch)]);
        SettingModel::query()->updateOrCreate(['key' => 'check_pv_num'], ['value' => json_encode($request->check_pv_num)]);
        SettingModel::query()->updateOrCreate(['key' => 'check_rate'], ['value' => json_encode($request->check_rate)]);
        return back();
    }

    /**
     * Build a form here.
     */
    public function form()
    {
        $this->switch('check_switch', '检测开关')->states([
            'on' => ['value' => 1, 'text' => '开', 'color' => 'primary'],
            'off' => ['value' => 0, 'text' => '关', 'color' => 'default'],
        ]);
        $this->number('check_pv_num', '检测pv')->style('width','150px')->help('每日最大导入PV');
        $this->rate('check_rate', '检测概率')->help('流量渠道跳转检测订单概率');


    }

    /**
     * The data of the form.
     *
     * @return array $data
     */
    public function data()
    {

        $check_switch = SettingModel::query()->firstOrCreate(['key' => 'check_switch'], ['value' => null]);
        $check_pv_num = SettingModel::query()->firstOrCreate(['key' => 'check_pv_num'], ['value' => null]);
        $check_rate = SettingModel::query()->firstOrCreate(['key' => 'check_rate'], ['value' => null]);

        return [
            'check_switch' => json_decode($check_switch->value),
            'check_pv_num'=> json_decode($check_pv_num->value),
            'check_rate'=> json_decode($check_rate->value),
        ];
    }
}
